import os
import win32gui  # pywin32-221.win-amd64-py3.7.exe
import win32con
from ctypes import *
import win32clipboard as w
import time
from PIL import Image  # pip install pillow
# pip install -i https://pypi.douban.com/simple pillow
import win32api


# 发送文字
def setText(info):
    w.OpenClipboard()
    w.EmptyClipboard()
    w.SetClipboardData(win32con.CF_UNICODETEXT, info)
    w.CloseClipboard()

# 发送图片
def setImage(imgpath):
    im = Image.open(imgpath)
    im.save('1.bmp')
    aString = windll.user32.LoadImageW(0, r"1.bmp", win32con.IMAGE_BITMAP, 0, 0, win32con.LR_LOADFROMFILE)

    if aString != 0:  ## 由于图片编码问题  图片载入失败的话  aString 就等于0
        w.OpenClipboard()
        w.EmptyClipboard()
        w.SetClipboardData(win32con.CF_BITMAP, aString)
        w.CloseClipboard()

    # 微信搜索框不会自动获取焦点，故需要模拟鼠标点击到搜索框的位置


def m_click(x, y):
    win32api.SetCursorPos((x, y))
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN, x, y, 0, 0)
    win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP, x, y, 0, 0)


def pasteInfo():
    win32api.keybd_event(17, 0, 0, 0)  # ctrl键位码是17
    win32api.keybd_event(86, 0, 0, 0)  # v键位码是86
    win32api.keybd_event(86, 0, win32con.KEYEVENTF_KEYUP, 0)  # 释放按键
    win32api.keybd_event(17, 0, win32con.KEYEVENTF_KEYUP, 0)


# 定位微信窗口，进行昵称备注的搜索（需点击两下才能获取到焦点）
def searchByUser(uname):
    hwnd = win32gui.FindWindow('WeChatMainWndForPC', '微信')
    setText(uname)
    m_click(100, 40)
    time.sleep(0.5)
    m_click(100, 40)
    pasteInfo()
    time.sleep(1)
    m_click(100, 120)  # 搜索到之后点击
    # win32api.keybd_event(13,0,0,0)#回车
    # win32api.keybd_event(13,0,KEYEVENTF_KEYUP,0)
    # win32gui.SendMessage(hwnd, win32con.WM_KEYDOWN, win32con.VK_RETURN, 0)
    # win32gui.SendMessage(hwnd, win32con.WM_KEYUP, win32con.VK_RETURN, 0)


def sendInfo():
    time.sleep(1)
    pasteInfo()
    time.sleep(1)
    win32api.keybd_event(18, 0, 0, 0)  # Alt
    win32api.keybd_event(83, 0, 0, 0)  # s
    win32api.keybd_event(83, 0, win32con.KEYEVENTF_KEYUP, 0)  # 释放按键
    win32api.keybd_event(18, 0, win32con.KEYEVENTF_KEYUP, 0)


# 发送完信息之后关闭窗口(跟QQ不一样，可以不关闭），接着搜索发送
def closeByUser(uname):
    hwnd = win32gui.FindWindow('WeChatMainWndForPC', '微信')
    win32api.keybd_event(18, 0, 0, 0)  # Alt
    win32api.keybd_event(115, 0, 0, 0)  # F4
    win32api.keybd_event(115, 0, KEYEVENTF_KEYUP, 0)
    win32api.keybd_event(18, 0, KEYEVENTF_KEYUP, 0)


#
# searchByUser('Tony老师')
# setText('Tony老师理发师')
# sendInfo()
# time.sleep(1)
# searchByUser('文件传输助手')
# setText('地表最强CPU')
# sendInfo()



# 获取无后缀的图片名称
def getNosuffixImgName(imgname):
    return os.path.splitext(imgname)[0]


imgdir = 'daily_picture/'
imgs = os.listdir(imgdir)
for img in imgs:
    searchByUser(getNosuffixImgName(img))
    setImage(imgdir + img)
    sendInfo()
    time.sleep(1)